#include "pthread.h"
#include "fcntl.h"
#include "unistd.h"
#include "stdio.h"
#include "time.h"

#include "datapool_mutex.h"
#include "Dual_Link_List.h"

void* data_read_thread(void* arg)
{
	printf("&data_read_thread: data read thread started.\n");

	int file_des;
	ssize_t read_size;
	int lock_ret_val, unlock_ret_val;
	void* buf = NULL;
	FILE* p_file;

	file_des = open("TestProject/Test_data/InputData", O_RDWR, 0666);
	if(-1 == file_des) {
		printf("&data_read_thread: Fail to open InputData file.\n");
		pthread_exit(NULL);
	}

/*	p_file = fopen("InputData", "r");
	if(NULL == p_file) {
		printf("Fail to open InputData file.\n");
		pthread_exit(NULL);
	}*/

	while(1) {
		buf = malloc(10);
		if(NULL == buf) {
			printf("&data_read_thread: fail to allocate memory for buffer, "
					"data read thread exit.\n");
			pthread_exit(NULL);
		}

		memset(buf, 0 , 10);

		read_size = read(file_des, buf, 1);

#ifdef DEBUG
		//printf( "The size of data readed is %d\n", (int8_t)arg );
		printf("&data_read_thread: The read thread has read %s from file.\n", (char*)buf);
#endif

		if(-1 == read_size) {
			printf("&data_read_thread: Fail to read data from input file.\n");
			pthread_exit(NULL);
		}
		else if(0 == read_size) {
			printf("&data_read_thread: The input file has been read to end,"
					" wait for 30 seconds.\n");
			sleep(30);
			continue;
		}

		lock_ret_val = pthread_mutex_lock(&mutex_list);
		if(0 != lock_ret_val) {
			printf("&data_read_thread: fail to lock mutex.\n");
			pthread_exit(NULL);
		}

		insert_node(p_list, get_length(p_list), buf);

		printf("&data_read_thread: pass insert.\n");

		//free(buf);

		unlock_ret_val = pthread_mutex_unlock(&mutex_list);
		if(0 != unlock_ret_val) {
			printf("&data_read_thread: Fail to unlock mutex.\n");
			pthread_exit(NULL);
		}
	}

	printf("&data_read_thread: Thread data_read_thread exit.\n");
	return NULL;
}
